<template>
  <view class="container">

    <!-- Statistics Cards -->
    <view class="stats-container">
      <view class="stats-card">
        <view class="stats-icon ongoing-icon">
          <uni-icons type="flag" size="22" color="#0ea5e9"></uni-icons>
        </view>
        <view class="stats-content">
          <text class="stats-number">{{ ongoingCount }}</text>
          <text class="stats-label">进行中</text>
        </view>
      </view>
      <view class="stats-card">
        <view class="stats-icon total-icon">
          <uni-icons type="medal" size="22" color="#8b6b4a"></uni-icons>
        </view>
        <view class="stats-content">
          <text class="stats-number">{{ totalCount }}</text>
          <text class="stats-label">总任务</text>
        </view>
      </view>
    </view>

    <!-- Tabs -->
    <view class="tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="['tab-item', activeTab === index ? 'active' : '']"
        @click="switchTab(index)"
      >
        <text :class="['tab-text', activeTab === index ? 'active-text' : '']">{{ tab }}</text>
      </view>
    </view>
    
    <!-- Content -->
    <view class="content">
      <!-- Loading state -->
      <view v-if="isLoading" class="loading-container">
        <uni-icons type="spinner-cycle" size="24" color="#8b6b4a"></uni-icons>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- Empty state -->
      <view v-else-if="myThemes.length === 0" class="empty-state">
        <uni-icons type="info" size="64" color="#d1ccc0"></uni-icons>
        <text class="empty-text">暂无{{ tabs[activeTab] }}打卡主题</text>
        <button class="empty-action" @click="navigateToDiscoverThemes">去发现主题</button>
      </view>
      
      <!-- Theme list -->
      <scroll-view v-else scroll-y="true" class="theme-list">
        <view 
          v-for="(theme, index) in myThemes" 
          :key="index"
          class="theme-card"
          @click="selectTheme(theme)"
        >
          <view class="card-left">
            <image :src="theme.imageUrl || defaultImage" mode="aspectFill" class="card-image"></image>
          </view>
          <view class="card-right">
            <text class="card-title">{{ theme.title }}</text>
            <view class="card-meta">
              <text class="card-meta-item">
                <text class="meta-icon">🏆</text>
                {{ theme.points || 0 }}分
              </text>
              <text class="card-meta-item">
                <text class="meta-icon">⏱️</text>
                {{ theme.duration || 0 }}小时
              </text>
            </view>
            <view class="card-status">
              <text :class="['status-tag', theme.statusClass]">{{ theme.statusText }}</text>
              <text class="check-date">{{ theme.checkDate }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useAuthStore } from '@/stores/auth';

export default {
  setup() {
    const authStore = useAuthStore();
    const tabs = ['全部', '进行中', '已完成'];
    const activeTab = ref(0);
    const isLoading = ref(true);
    const allThemes = ref([]);
    const defaultImage = 'https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?auto=format&fit=crop&q=80&w=300';

    // Compute statistics
    const totalCount = computed(() => allThemes.value.length);
    const ongoingCount = computed(() => allThemes.value.filter(theme => theme.status === 'ongoing').length);

    // Filtered themes based on active tab
    const myThemes = computed(() => {
      if (activeTab.value === 0) return allThemes.value;
      if (activeTab.value === 1) return allThemes.value.filter(theme => theme.status === 'ongoing');
      if (activeTab.value === 2) return allThemes.value.filter(theme => theme.status === 'completed');
      return allThemes.value;
    });

    // Switch between tabs
    function switchTab(index) {
      activeTab.value = index;
    }

    // Navigate back
    function goBack() {
      uni.navigateBack();
    }

    // Navigate to discover themes
    function navigateToDiscoverThemes() {
      uni.navigateBack({
        success: () => {
          uni.showToast({
            title: '浏览推荐主题',
            icon: 'none'
          });
        }
      });
    }

    // Select a theme to continue or view details
    function selectTheme(theme) {
      uni.navigateTo({
        url: `/pages/daka/daka?theme=${encodeURIComponent(theme.title)}&themeId=${encodeURIComponent(theme.id || '')}`
      });
    }

    // Fetch user's check-in themes
    function fetchMyThemes() {
      isLoading.value = true;
      
      // Check if user is logged in
      if (!authStore.isLoggedIn) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        isLoading.value = false;
        return;
      }
      
      // Fetch from API
      const userId = authStore.userInfo?.id || authStore.open_id || authStore.union_id || '123456';
      
      uni.request({
        url: 'https://tushuoit.com/api/ju/gis/map/show/topics?user_id=' + userId + '&recently_day=100',
        method: 'POST',
        data: '',
        header: {
          'accept': 'application/json'
        },
        success: (res) => {
          if (res.data && res.data.code === 0 && res.data.data) {
            // Transform the data
            allThemes.value = processThemeData(res.data.data);
          } else {
            // Handle error
            uni.showToast({
              title: res.data?.message || '获取数据失败',
              icon: 'none'
            });
            
            // For demo purposes, add some mock data if API fails
            allThemes.value = createMockData();
          }
        },
        fail: (err) => {
          console.error('获取我的打卡主题失败', err);
          uni.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
          
          // For demo purposes, add some mock data if API fails
          allThemes.value = createMockData();
        },
        complete: () => {
          isLoading.value = false;
        }
      });
    }

    // Process the theme data from API
    function processThemeData(data) {
      return data.map(item => {
        // Determine status based on completion
        // Check if all checkpoints are visited by comparing checked_scenic_counts with required_checkpoints
        const totalCheckpoints = item.route_metadata?.required_checkpoints || 0;
        const checkedCheckpoints = parseInt(item.checked_scenic_counts || '0', 10);
        const isCompleted = checkedCheckpoints >= totalCheckpoints;
        const status = isCompleted ? 'completed' : 'ongoing';
        
        // Get the first checkpoint image as theme image
        let imageUrl = defaultImage;
        if (item.route_metadata && 
            item.route_metadata.checkpoints && 
            item.route_metadata.checkpoints.length > 0 &&
            item.route_metadata.checkpoints[0].scenic_img_url) {
          imageUrl = item.route_metadata.checkpoints[0].scenic_img_url;
        }
        
        // Format check-in date
        const checkDate = formatCheckDate(item.created_at || item.updated_at);
        
        return {
          id: item.id || '',
          title: item.topic?.replace(/�/g, '') || '未命名主题',
          points: item.sum_points || 0,
          duration: item.spend_all_time || 0,
          imageUrl: imageUrl,
          status: status,
          statusText: isCompleted ? '已完成' : '进行中',
          statusClass: isCompleted ? 'status-completed' : 'status-ongoing',
          checkDate: checkDate,
          raw: item // Keep the raw data for reference
        };
      });
    }

    // Format date for display
    function formatCheckDate(dateStr) {
      if (!dateStr) return '未知时间';
      
      try {
        const date = new Date(dateStr);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
      } catch (e) {
        return '未知时间';
      }
    }

    // Create mock data for demo
    function createMockData() {
      return [
        {
          id: 'theme1',
          title: '莒县文化之旅',
          points: 120,
          duration: 3,
          imageUrl: 'https://images.unsplash.com/photo-1518709766631-a6a7f45921c3?auto=format&fit=crop&q=80&w=300',
          status: 'ongoing',
          statusText: '进行中',
          statusClass: 'status-ongoing',
          checkDate: '2023-05-15'
        },
        {
          id: 'theme2',
          title: '红色记忆探访',
          points: 90,
          duration: 2,
          imageUrl: 'https://images.unsplash.com/photo-1528164344705-47542687000d?auto=format&fit=crop&q=80&w=300',
          status: 'completed',
          statusText: '已完成',
          statusClass: 'status-completed',
          checkDate: '2023-04-22'
        },
        {
          id: 'theme3',
          title: '莒县自然风光游',
          points: 150,
          duration: 4,
          imageUrl: 'https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?auto=format&fit=crop&q=80&w=300',
          status: 'completed',
          statusText: '已完成',
          statusClass: 'status-completed',
          checkDate: '2023-03-30'
        }
      ];
    }

    onMounted(() => {
      fetchMyThemes();
    });

    return {
      tabs,
      activeTab,
      isLoading,
      myThemes,
      defaultImage,
      totalCount,
      ongoingCount,
      switchTab,
      goBack,
      navigateToDiscoverThemes,
      selectTheme
    };
  }
};
</script>

<style>
.container {
  background-color: #f8f0e3;
  min-height: 100vh;
}

/* Header */
.header {
  position: relative;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.back-button {
  position: absolute;
  left: 10px;
  padding: 10px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* Statistics Cards */
.stats-container {
  display: flex;
  padding: 15px;
  gap: 10px;
  background-color: #fff;
}

.stats-card {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f9f5ec;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.stats-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
}

.ongoing-icon {
  background-color: #e0f2fe;
}

.total-icon {
  background-color: #f3e8d8;
}

.stats-content {
  display: flex;
  flex-direction: column;
}

.stats-number {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.stats-label {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

/* Tabs */
.tabs {
  display: flex;
  background-color: #fff;
  padding: 0 10px;
  border-bottom: 1px solid #f0e6d2;
}

.tab-item {
  flex: 1;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 25%;
  width: 50%;
  height: 3px;
  background-color: #8b6b4a;
  border-radius: 3px 3px 0 0;
}

.tab-text {
  font-size: 15px;
  color: #999;
}

.active-text {
  font-weight: bold;
  color: #333;
}

/* Content */
.content {
  flex: 1;
  padding: 10px;
}

/* Loading container */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.loading-text {
  margin-top: 10px;
  font-size: 14px;
  color: #8b6b4a;
}

/* Empty state */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
}

.empty-text {
  margin-top: 20px;
  font-size: 16px;
  color: #999;
}

.empty-action {
  margin-top: 20px;
  background-color: #8b6b4a;
  color: white;
  font-size: 14px;
  padding: 8px 20px;
  border-radius: 20px;
}

/* Theme list */
.theme-list {
  height: calc(100vh - 180px); /* Adjusted to account for stats cards */
}

.theme-card {
  display: flex;
  background-color: #fff;
  border-radius: 10px;
  margin-bottom: 10px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.card-left {
  width: 80px;
  height: 80px;
}

.card-image {
  width: 100%;
  height: 100%;
}

.card-right {
  flex: 1;
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.card-meta {
  display: flex;
  margin-bottom: 8px;
}

.card-meta-item {
  font-size: 12px;
  color: #666;
  margin-right: 10px;
  display: flex;
  align-items: center;
}

.meta-icon {
  margin-right: 4px;
}

.card-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-tag {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
}

.status-ongoing {
  background-color: #f0f9ff;
  color: #0ea5e9;
}

.status-completed {
  background-color: #ecfdf5;
  color: #10b981;
}

.check-date {
  font-size: 12px;
  color: #999;
}
</style>
